package org.totoro.amap.service.impl;

import com.googlecode.javaewah.datastructure.BitSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.totoro.dto.HitTag;
import org.totoro.dto.MultipleTag;
import org.totoro.enums.Strategy;
import org.totoro.amap.service.AbstractBitmap;
import org.totoro.amap.service.BitmapTagService;

import java.util.List;

/**
 * @author daocr
 * @date 2019-04-26
 */
public class RedisBitImpl extends AbstractBitmap implements BitmapTagService {


    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public HitTag match(MultipleTag multipleTag, List<Long> ids) {

        return null;
    }

    @Override
    public HitTag match(List<MultipleTag> multipleTag, List<Long> ids) {

        BitSet bitSet = super.find(multipleTag, ids);

        return new HitTag(Strategy.conv(bitSet));
    }


    @Override
    public BitSet getBitmapByTagName(String tagName) {
        return conv(redisTemplate.opsForValue().get(tagName));
    }

    private BitSet conv(String tagName) {

        byte[] bytes = redisTemplate.opsForValue().get(tagName).getBytes();

        final BitSet bits = new BitSet();
        for (int i = 0; i < bytes.length * 8; i++) {
            if ((bytes[i / 8] & (1 << (7 - (i % 8)))) != 0) {
                bits.set(i);
            }
        }
        return bits;
    }
}
